package haxeframe.utils;

class ObjectPool
{

	private var _pool:Array<Dynamic>;
	private var _params:Array<Dynamic>;
	public var length(get, never):Int;
	private var objectClass:Class<Dynamic>;

	public var name:String;

	private var _created:Int = 0;
	
	public function new(type:Class<Dynamic>, params:Array<Dynamic>, initialLength:Int=1)
	{
		objectClass = type;
		_params = params;
		_pool = new Array<Dynamic>();
		while(length < initialLength)
			_pool.push(createObject());
	}

	public function ObjectPool()
	{
	}

	public function get_length():Int
	{
		return _pool.length;
	}
	
	private function createObject():Dynamic
	{
		++_created;
		return Type.createInstance(objectClass, _params);
	}

	public function getObject():Dynamic
	{
		if(length == 0){
			return createObject();
		} else {
			return _pool.shift();
		}
	}
	
	public function returnObject(o:Dynamic):Void
	{
		_pool.push(o);
	}
	
	public function destroy():Void
	{
		objectClass = null;
		_params = null;
		_pool = new Array<Dynamic>();
	}
}